mui.init();
mui.plusReady(function() {
	var storage = plus.storage,
		segmentedControlBtns = [].slice.call(document.querySelectorAll(".mui-control-item")), 
		pullCount = 5,
		currentDepartmentId = "11",
		currentDepartment = "",
		oldIndex = 0;
	// 页面初始化
	// pageRefresh();
	
	// 绑定切换选项卡时的事件处理函数
	document.getElementById('slider').addEventListener('slide', function(e) {
		var newIndex = e.detail.slideNumber;
		if(oldIndex !== newIndex) {
			oldIndex = newIndex++;
			var item = document.getElementById("item" + newIndex),
				department = item.getAttribute("data-department");
			if(department !== currentDepartmentId) {
				showSpinner();
				pageRefresh();
			}
		}
	}, false);
	
	// 渲染侧滑菜单
	var urlPrefix = "https://bird.ioliu.cn/v1?url=";
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=index&a=getDepartmentList&hospitalid=10&uid=3&token=dfaf", {
		async: true,
		type: "GET",
		dataType: "json",
		beforeSend: function() {
			if(plus.networkinfo.getCurrentType() === 1) {
				var departmentList = storage.getItem("department_list_in_equipment_manage");
				if(departmentList) {
					var data = JSON.parse(departmentList);
					renderOffsetMenu(data);
				}
				return false;
			}
		},
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data;
				if(data.length) {
					renderOffsetMenu(data);
					storage.setItem("department_list_in_equipment_manage", JSON.stringify(data));
				}
			}
		}
	});
	
	(function($) {
		//阻尼系数
		var deceleration = mui.os.ios?0.003:0.0009;
		$('.mui-scroll-wrapper').scroll({
			bounce: false,
			indicators: true, //是否显示滚动条
			deceleration:deceleration
		});
		$.ready(function() {
			//循环初始化所有下拉刷新，上拉加载。
			$.each(document.querySelectorAll('.mui-slider-group .mui-scroll'), function(index, pullRefreshEl) {
				$(pullRefreshEl).pullToRefresh({
					down: {
						callback: function() {
							var self = this;
							setTimeout(function() {
								var container = self.element.querySelector('.item-content'),
									activeSliderBtn = document.querySelector(".mui-control-item.mui-active"),
									index = segmentedControlBtns.indexOf(activeSliderBtn) + 1,
									item = document.getElementById("item" + index),
									storageKey = "department" + currentDepartmentId + "_equipment_item" + index;
								if(plus.networkinfo.getCurrentType() !== 1) {
									pullData(index, currentDepartmentId, pullCount, function(html) {
										if(html) {
											container.innerHTML = html;
											bindLinkNormalTapEvent(item); // 正常联网时可以进入设备详情页
										} else {
											item.querySelector(".mui-pull-bottom-tips").style.display = "none";
											container.innerHTML = "<p class='no-data'>暂时没有相关数据</p>";
										}
										mui.toast("数据加载完毕！");
										storage.setItem(storageKey, html);
									});
								} else {
									mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
								}
								self.endPullDownToRefresh();
							}, 1000);
						}
					},
					up: {
						callback: function() {
							var self = this;
							setTimeout(function() {
								var container = self.element.querySelector('.item-content'),
									ul = container.querySelector('.mui-table-view'),
									activeSliderBtn = document.querySelector(".mui-control-item.mui-active"),
									index = segmentedControlBtns.indexOf(activeSliderBtn) + 1,
									storageKey = "department" + currentDepartmentId + "_equipment_item" + index,
									item = document.getElementById("item" + index);
								if(ul) {
									var childNodes = childNodesCount(ul);
									// 设备列表存在时，直接向列表中追加上拉时拉取获得的数据
									if(plus.networkinfo.getCurrentType() !== 1) {
										pullMoreData(index, currentDepartmentId, pullCount, childNodes, function(html) {
											ul.innerHTML += html;
											bindLinkNormalTapEvent(item);
											
											if(html) {
												var storageData = storage.getItem(storageKey);
												storage.setItem(storageKey, storageData.replace("</ul>", html + "</ul>"));
												mui.toast("数据加载完毕~");
											} else {
												mui.toast("没有更多数据了");
											}
										});
									} else {
										mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
									}
								} else {
									// 如果设备列表不存在，拉取数据，并创建列表，往列表中添加数据
									if(plus.networkinfo.getCurrentType() !== 1) {
										pullData(index, currentDepartmentId, pullCount, function(html) {
											if(html) {
												container.innerHTML = html;
												bindLinkNormalTapEvent(item);
											} else {
												item.querySelector(".mui-pull-bottom-tips").style.display = "none";
												container.innerHTML = "<p class='no-data'>暂时没有相关数据</p>";
											}
											mui.toast("数据加载完毕！");
											storage.setItem(storageKey, html);
										});
									} else {
										mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
									}
								}
								self.endPullUpToRefresh();
							}, 1000);
						}
					}
				});
			});
		});
	})(mui);
	
	
	function pageRefresh() {
		var h1 = document.querySelector("#header h1"),
			activeSliderBtn = document.querySelector(".mui-control-item.mui-active"),
			index = segmentedControlBtns.indexOf(activeSliderBtn) + 1,
			item = document.getElementById("item" + index);
		
		h1.innerHTML = currentDepartment ? "设备型号（" + currentDepartment + "）" : "设备型号";
		
		if (plus.networkinfo.getCurrentType() !== 1) {
			pullData(index, currentDepartmentId, pullCount, function(html) {
				if(html) {
					item.querySelector('.item-content').innerHTML = html;					
					bindLinkNormalTapEvent(item);
				} else {
					item.querySelector(".mui-pull-bottom-tips").style.display = "none";
					item.querySelector('.item-content').innerHTML = "<p class='no-data'>暂时没有相关数据</p>";
				}
				item.setAttribute("data-department", currentDepartmentId);
				alert("department" + currentDepartmentId + "_equipment_item" + index + ":" + html);
				// 更新本地存储的数据
				storage.setItem("department" + currentDepartmentId + "_equipment_item" + index, html);
			});
		} else {
			var storageData = storage.getItem("department" + currentDepartmentId + "_equipment_item" + index);
			if (storageData) {
				item.querySelector('.item-content').innerHTML = storageData;
				bindLinkOfflineTapEvent(item);
			} else {
				item.querySelector(".item-content").innerHTML = "<div class='network-error'><p><span class='network-error-icon'><i class='fa fa-exclamation-circle' aria-hidden='true'></i></span></p><p>连接超时</p></div>";
				mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
			}
		}
	}
	
	
	function renderOffsetMenu(data) {
		var html = "<ul class='mui-table-view'>",
			list = document.getElementById("offset-menu-list");
		for(var i = 0, length = data.length; i < length; i++) {
			html += "<li class='mui-table-view-cell' data-departmentid='" + data[i].id + "'>" + data[i].name + "</li>";
		}
		html += "</ul>";
		list.innerHTML += html;
		
		var lis = list.querySelectorAll("li");
		[].slice.call(lis).forEach(function(v) {
			v.addEventListener("tap", function() {
				currentDepartmentId = this.getAttribute("data-departmentid");
				currentDepartment = this.innerText;
				mui('.mui-off-canvas-wrap').offCanvas().close();
				pageRefresh(true);
				var addActive = removeActive = false;
				for(var i = 0, length = lis.length; i < length; i++) {
					if(!removeActive && lis[i].classList.contains("active-item")) {
						if(lis[i].getAttribute("data-departmentid") === currentDepartmentId) break;
						lis[i].classList.remove("active-item");
						removeActive = true;
						if(addActive) break;
					}
					if(!addActive && lis[i].getAttribute("data-departmentid") === currentDepartmentId) {
						lis[i].classList.add("active-item");
						addActive = true;
						if(removeActive) break;
					}
				}
			});
		});
	}
	
	// 显示加载时旋转图标
	function showSpinner() {
		var activeSliderBtn = document.querySelector(".mui-control-item.mui-active"),
			index = segmentedControlBtns.indexOf(activeSliderBtn) + 1,
			item = document.getElementById("item" + index),
			spinner = '<div class="mui-loading"><div class="mui-spinner"></div></div>';
		if(!item.querySelector('.mui-loading')) {
			item.querySelector(".item-content").innerHTML = spinner;
		}
	}
});


/*
 * 功能：拉取设备列表数据
 * 参数含义：
 * mainType：指定要拉取“所有设备”还是“我的设备”列表数据
 * subType：指定要拉取某个子选项卡下包含的数据
 * count：指定拉取条目的最大数目
 * callback：回调，可以接收获取到的HTML字符串作为参数
 * 
 * */
function pullData(subType, departmentid, count, callback) {
	var urlPrefix = "https://bird.ioliu.cn/v1?url=",
		rootPath = "http://app.xiaoweicanting.com/";
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getEquipmentList&hospitalid=10&departmentid=" + departmentid + "&uid=3&token=dfaf&skip=0&limit=" + count + "&state=" + subType, {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data,
					length = data.length, html;
				if(length) {
					html = '<ul class="mui-table-view">';
					for(var i = 0; i < length; i++) {
						html += '<li class="mui-table-view-cell">' + 
									'<a href="javascript:;" data-sid="' + data[i].sid + '">' + 
										'<p class="submit-time mui-pull-right">' + data[i].addtime + '</p>' + 
										'<h4>' + data[i].equipmentname + '</h4>' + 
										'<div class="list-item-body">' + 
											'<div class="text-align-right mui-pull-right">' + 
												'<div class="text-align-center">' + 
													'<img id="doctor-display" onload="load(this)" src="../../images/test/timg.jpeg" data-src="' + rootPath + data[i].adduimg + '" />' + 
													'<p class="doctor-name">' + data[i].addname + '</p>' + 
													'<p class="doctor-type">科室：' + data[i].departmentname + '</p>' + 
												'</div>' + 
											'</div>' +
											'<div class="mui-media-body">' + 
												'<div id="equipment-image">' + 
													'<img onload="load(this)" src="../../images/test/timg.jpeg" data-src="' + rootPath + data[i].epic + '" />' + 
												'</div>' + 
												'<ul class="equipment-items">' + 
													'<li>科室：' + data[i].departmentname + '</li>' + 
													'<li>设备类型：' + data[i].modeltype + '</li>' + 
													'<li>设备型号：' + data[i].spectype + '</li>' + 
													'<li>资产编号：' + data[i].assetsid + '</li>' + 
													'<li>保修截止：' + data[i].guaranteetime + '</li>' + 
												'</ul>' + 
											'</div>' + 
										'</div>' + 
									'</a>' + 
								'</li>';
					}
					html += '</ul>';
				}
				callback(html);
			}
		}
	});
}
/*
 
 * 功能：专门用于在用户上拉列表且列表存在时向后台拉取更多数据
 * mainType：指定要拉取“所有设备”还是“我的设备”列表数据
 * subType：指定要拉取某个子选项卡下包含的数据
 * currentCount：当前列表中包含的条目数量
 * pullcount：指定每次加载的条目数量
 * callback：回调，可以接收一个表示是否还有更多数据的布尔值done以及获取到的HTML字符串作为参数
 * 特别指出的是，回调函数接收的参数html如果为0，表示当前选项卡之下已经没有任何数据，需要对当前列表进行清空；
 * 如果html为空字符串，则表示当前列表下没有更多数据，不需要添加更多的数据。
 * */
function pullMoreData(subType, departmentid, pullCount, currentCount, callback) {
	var urlPrefix = "https://bird.ioliu.cn/v1?url=",
		rootPath = "http://app.xiaoweicanting.com/";
	mui.ajax(urlPrefix + "http://app.xiaoweicanting.com/hospital.php?m=App&c=equipment&a=getEquipmentList&hospitalid=10&departmentid=" + departmentid + "&uid=3&token=dfaf&skip=" + currentCount + "&limit=" + pullCount + "&state=" + subType, {
		async: true,
		type: "GET",
		dataType: "json",
		success: function(data, textStatus) {
			if(textStatus === "success") {
				var data = data.data,
					length = data.length, html = "", len;
				if(length) {
					for(var i = 0; i < length; i++) {
						html += '<li class="mui-table-view-cell">' + 
									'<a href="javascript:;" data-sid="' + data[i].sid + '">' + 
										'<p class="submit-time mui-pull-right">' + data[i].addtime + '</p>' + 
										'<h4>' + data[i].equipmentname + '</h4>' + 
										'<div class="list-item-body">' + 
											'<div class="text-align-right mui-pull-right">' + 
												'<div class="text-align-center">' + 
													'<img id="doctor-display" src="../../images/test/timg.jpeg" data-src="' + rootPath + data[i].adduimg + '" onload="load(this)" />' + 
													'<p class="doctor-name">' + data[i].addname + '</p>' + 
													'<p class="doctor-type">科室：' + data[i].departmentname + '</p>' + 
													'</div>' + 
												'</div>' + 
												'<div class="mui-media-body">' + 
													'<div id="equipment-image">' + 
														'<img src="../../images/test/timg.jpeg" data-src="' + rootPath + data[i].epic + '" onload="load(this)" />' + 
													'</div>' + 
													'<ul class="equipment-items">' + 
														'<li>科室：' + data[i].departmentname + '</li>' + 
														'<li>设备类型：' + data[i].modeltype + '</li>' + 
														'<li>设备型号：' + data[i].spectype + '</li>' + 
														'<li>资产编号：' + data[i].assetsid + '</li>' + 
														'<li>保修截止：' + data[i].guaranteetime + '</li>' + 
													'</ul>' + 
												'</div>' + 
											'</div>' + 
										'</a>' + 
									'</li>';
					}
				}
				callback(html);
			}
		}
	});
}


function bindLinkNormalTapEvent(item) {
	[].slice.call(item.querySelectorAll("a")).forEach(function(v) {
		v.addEventListener("tap", function() {
			turnToEquipmentDetail(this.getAttribute("data-sid"));
		}, false);
	});
}

function bindLinkOfflineTapEvent(item) {
	[].slice.call(item.querySelectorAll("a")).forEach(function(v) {
		v.addEventListener("tap", function() {
			mui.toast("网络好像有点小问题，\r\n请检查网络连接~");
		}, false);
	});
}

// 计算给定节点下包含的元素节点个数
function childNodesCount(node) {
	var count = 0, childNodes = node.childNodes;
	for(var i = 0, len = childNodes.length; i < len; i++) {
		if (childNodes[i].nodeType === 1) {
			count++;
		}
	}
	return count;
}

function turnToEquipmentDetail(id) {
	mui.openWindow({
		url: "equipment_detail.html",
		extras: {
			equipmentId: id
		},
		styles: {
			scrollIndicator: "none"
		}
	});
}